<template>
  <div class="flex flex-col mt-1 overflow-hidden">
    <!-- <a-input-search v-model:value="searchKey" placeholder="病历名称/助记码" class="my-2" @search="getTree" /> -->
    <a-spin :spinning="loading" class="h-full" wrapper-class-name="h-full">
      <a-directory-tree
        v-if="treeData.length"
        :key="treeData.length"
        v-model:selected-keys="selectedKeys"
        v-model:expanded-keys="expandedKeys"
        :tree-data="treeData"
        class="h-full overflow-hidden overflow-x-auto"
        :field-names="{
          key: 'treeId'
        }"
      >
        <template #icon="{ template }">
          <img v-if="template" :src="IconDocument" width="14" class="pb-1" />
          <img v-else :src="IconDirectory" width="14" class="pb-1" />
        </template>
        <template #title="item">
          <div class="inline-flex justify-between items-center w-full" @click="onSelectEmr(item)">
            <div v-if="item.template" class="mr-2 truncate w-36" :title="item.templateName">
              <div>{{ item.templateName }}</div>
              <div class="text-grey text-xs">{{ dayjs(item.createTime).format('YYYY-MM-DD HH:mm') }}</div>
            </div>
            <div v-else class="mr-4 truncate w-36" :title="item.categoryName">{{ item.categoryName }}</div>
            <div v-if="canEdit" class="flex items-center">
              <template v-if="item.template">
                <a-dropdown placement="bottomLeft" :disabled="item.templateStatus === '1'">
                  <template #overlay>
                    <a-menu class="text-center">
                      <a-menu-item>
                        <BaseButton size="small" type="link" disabled @click="onAddTemplate(item)"> 修改 </BaseButton>
                      </a-menu-item>
                      <a-menu-item>
                        <BaseButton danger size="small" type="link" confirm-text="确定删除该病历?" @click="onDeleteTemplate(item.id)">删除</BaseButton>
                      </a-menu-item>
                    </a-menu>
                  </template>
                  <a-button type="text" :icon="h(MoreOutlined)" size="small" />
                </a-dropdown>
              </template>
              <a-space v-else>
                <!-- <BaseButton size="small" type="text" danger :icon="h(CloseOutlined)" confirm-text="确定删除该目录?" @click="onDeleteDrectory(item)" /> -->
                <!-- <a-button type="text" :icon="h(PlusOutlined)" size="small" @click.stop="onAddTemplate(item, true)" /> -->
              </a-space>
            </div>
          </div>
        </template>
      </a-directory-tree>
      <a-empty v-else class="w-full h-full" />
    </a-spin>
  </div>
</template>

<script setup>
import { ref, h, onMounted, watch } from 'vue'
import { MoreOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import IconDirectory from '@/assets/icons/icon-directory.svg'
import IconDocument from '@/assets/icons/icon-document.svg'
import useStore from '@/views/out-doctor/store.js'

const props = defineProps({
  canEdit: {
    type: Boolean,
    default: false
  },
  emrLoading: {
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['select', 'refresh'])
const store = useStore()

const loading = ref(true)
const openTemplate = ref(false)

const treeData = ref([])
const childrenList = ref([])
const selectedKeys = ref([])
const expandedKeys = ref([])
const templateRowData = ref({})

let fetchFlag = 1
// 获取文书
const getTree = async () => {
  // treeData.value = []
  loading.value = true
  const checkFlag = ++fetchFlag

  const { code, data, msg } = await post('/emr/emrCategory/getEmrCategoryTreeTempleteId', {
    categroyTypes: [0, 4],
    brId: store.currentPatient.brId,
    jzbh: store.currentPatient.jzbh
  })
  loading.value = false
  if (code !== 0) return message.error(msg)
  if (checkFlag !== fetchFlag) return console.info('[Warn] 重复请求已忽略', `【getEmrCategoryTreeTempleteId】`)

  if (data.length === 0) return (treeData.value = [])
  // treeData.value = data

  treeData.value = getHistory(data) || []
  childrenList.value = treeData.value.map((item) => item.children).flat()
  store.outDoctorEmrId = childrenList.value[0].id
  expandedKeys.value = data.map((item) => item.treeId)
}
const getHistory = (data) => {
  const dataSource = JSON.parse(JSON.stringify(data))
  dataSource.forEach((item) => {
    if (item.categoryType === 0 && item.children?.length) {
      const currentChildren = item.children.filter((child) => child.lsh === store.currentPatient.jzbh)
      const historyChildren = item.children.filter((child) => child.lsh !== store.currentPatient.jzbh)
      if (historyChildren.length) {
        currentChildren.push({ id: 'LISI', treeId: 'LISI', categoryName: '历史病历', children: historyChildren })
      }
      item.children = currentChildren
    }
  })
  return dataSource
}
watch(
  () => [props.emrLoading, childrenList.value],
  () => {
    if (!props.emrLoading && childrenList.value.length) {
      const currentInfo = childrenList.value.find((item) => item.id === store.currentEMR?.id) || {}
      if (currentInfo.id) {
        onSelectEmr(currentInfo)
      } else {
        onSelectEmr(childrenList.value[0])
      }
    }
  }
)
watch(
  () => store.currentEMR,
  (val) => {
    if (val.id) {
      selectedKeys.value = [val.id]
    } else {
      selectedKeys.value = []
    }
  }
)

// 修改病历
const onAddTemplate = (row, isAdd = false) => {
  openTemplate.value = true
  if (isAdd) {
    templateRowData.value = {
      id: '',
      categoryName: row.categoryName,
      categroyId: row.id
    }
  } else {
    templateRowData.value = { ...row }
  }
}

// // 删除目录
// const onDeleteDrectory = async (row) => {
//   const { code, msg } = await post('/emr/emrCategory/doDelEmrCategory/' + row.id)
//   if (code !== 0) return message.error(msg)
//   message.success('删除成功')
//   getTree()
// }
// 删除病历
const onDeleteTemplate = async (id, isQuery = true) => {
  const { code, msg } = await post('/emr/emrCategory/doDelTempleteFromEmrCategory', {
    id
  })
  if (code !== 0) return message.error(msg)
  if (store.currentEMR?.id === id) {
    onSelectEmr(childrenList.value[0])
  }
  isQuery && message.success('删除成功')
  isQuery && getTree()
}

// 点击病历
const onSelectEmr = (row = {}) => {
  if (!row.template) return
  if (row.id) {
    store.currentEMR = row
    emit('select')
  }
}
onMounted(() => {
  store.currentEMR = {}
  getTree()
})
defineExpose({
  getTree: getTree,
  onDeleteTemplate: onDeleteTemplate
})
</script>
<style lang="less" scoped>
.icon-color {
  color: var(--primary-color);
}
:deep(.ant-spin-container) {
  display: flex;
  flex-direction: column;
  height: 100%;
}
:deep(.ant-tree) {
  .ant-tree-list {
    height: 100%;
    overflow: auto;
  }
  .ant-tree-switcher {
    width: 16px !important;
  }
}
:deep(.ant-tree-indent-unit) {
  width: 16px !important;
}
:deep(.ant-tree-treenode-selected) {
  .text-grey {
    color: #fff !important;
  }
}
:deep(.ant-tree-treenode) {
  display: flex;
  width: 100%;
  padding: 8px 0;
  button:not(.ant-btn-dangerous) {
    color: var(--primary-color);
  }
  .ant-tree-node-selected {
    button:not(.ant-btn-dangerous) {
      color: #fff;
    }
  }

  &:before {
    bottom: 0 !important;
  }
  .ant-tree-node-content-wrapper {
    display: flex;
    align-items: flex-start;

    .ant-tree-title {
      flex: 1;
    }
  }
}
.radio-style {
  display: flex;
  :deep(.ant-radio-button-wrapper) {
    // width: 33.3%;
    flex: 1;
    padding: 0;
    text-align: center;
  }
}
</style>
